package com.breaktian.assemble.router;


import com.breaktian.assemble.utils.LogUtil;
import com.breaktian.assemble.router.i.IRouterTable;
import com.breaktian.assemble.router.parse.Rule;

import java.util.HashMap;
import java.util.List;

/**
 * Created by keke.tian on 2017/7/26.
 */

public class RouterTable implements IRouterTable {

    static class InstanceHolder{
        static final RouterTable instance = new RouterTable();
        //路由表
        static final HashMap<String,Rule> routerTable = new HashMap<String,Rule>();
    }

    public static RouterTable get(){
        return InstanceHolder.instance;
    }

    @Override
    public HashMap<String, Rule> getRouterTable() {
        return InstanceHolder.routerTable;
    }

    @Override
    public void importRouterTable(List<Rule> ruleList) {
        getRouterTable().clear();//防止多次加载导致内存溢出
        if(ruleList!=null&&ruleList.size()>0){
            for (Rule rule:ruleList) {
                addRouterRule(rule.getSchema(),rule);
            }
        }
    }

    /**
     * 增
     * @param schema 自定义
     * @param rule
     * */
    @Override
    public void addRouterRule(String schema,Rule rule){
        LogUtil.d("add router rule");
        getRouterTable().put(schema,rule);
    }

    /**
     * 删
     *
     * */
    @Override
    public void delRouterRule(String schema) {
        LogUtil.d("delete router rule");
        getRouterTable().remove(schema);
    }

    /**
     * 改
     *
     * */
    @Override
    public void modRouterRule(String schema, Rule rule) {
        LogUtil.d("mod router rule");
        if(getRouterTable().containsKey(schema)){
            addRouterRule(schema,rule);//如果有重复的会自动覆盖
        }else{
            LogUtil.w("can not find schema from router table");
        }
    }


    /**
     * 查
     *
     * */
    @Override
    public Rule getRule(String schema) {
        return getRouterTable().get(schema);
    }


}
